import pymysql
from pyecharts.charts import Pie
from pyecharts import options

# 连接数据库
db = pymysql.connect(
    host="localhost",
    user="root",
    password="123456",
    database="crawlerdemo",
    charset="utf8"
)

# 创建游标对象
cursor = db.cursor()

# SQL查询语句
sql = "SELECT job_place, COUNT(job_id) FROM job GROUP BY job_place ORDER BY COUNT(job_id) DESC LIMIT 5"

try:
    cursor.execute(sql)
    res = cursor.fetchall()
    pie = Pie()
    # 确保res中的数据格式正确，例如 [('北京', 100), ('上海', 90), ...]
    pie.add("单位/个", [list(x) for x in res])
    # 创建饼图对象
    pie.set_global_opts(title_opts=options.TitleOpts(title="岗位数量最多的五个城市"))
    pie.render("pienum.html")
except Exception as e:
    print("查询出错啦:", e)
finally:
    cursor.close()
    db.close()